package com.smart.dao;

import com.smart.domain.Calender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Repository
public class Calenderdao {
    private JdbcTemplate jdbcTemplate;
    @Autowired
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    //插入日历数据
    public int  addcalender(Calender calender)
    {
      String sql = "insert into user_calender (user_term,user_weeks,user_startday,user_stopday) values(?,?,?,?)";
      Object[] cal =new Object[]{calender.getTerm(),calender.getWeek(),calender.getStartday(),calender.getStopday()};
      return jdbcTemplate.update(sql,cal);
    }


    //删除，将满足条件user_term=? and user_startday=?的删除
    public int deletecalender(Calender calender)
    {
        String sql="delete from user_calender where user_term=? and user_startday=?";
        return jdbcTemplate.update(sql,calender.getTerm(),calender.getStartday());
    }


    //修改,将满足条件 user_term =?的周次及开始结束时间更改
    public  int updatecalender(Calender calender)
    {
        String sql ="update user_calender set user_weeks=?,user_startday=?,user_stopday=? where user_term =?";
        return jdbcTemplate.update(sql,calender.getWeek(),calender.getStartday(),calender.getStopday(),calender.getTerm());
    }

    //查询,满足条件user_weeks=?的记录
    public void querycalender(Calender calender){

        String sql ="select * from user_calender where user_weeks=?";
        List<Map<String, Object>> calender1=jdbcTemplate.queryForList(sql,calender.getWeek());
        System.out.println(calender1);
    }

    //查询表中的各个记录
    public void querycalenderlist(){
        String sql ="select * from user_calender";
        List<Calender> calenderAS =jdbcTemplate.query(sql, new CalenderRowMapper());
        System.out.println(calenderAS);
    }



}
class CalenderRowMapper implements RowMapper<Calender> {
    @Override
    public Calender mapRow(ResultSet cal, int i) throws SQLException {

        //1 从结果集里得到数据
        int term =cal.getInt("user_term");
        int week = cal.getInt("user_weeks");

        Date startday= cal.getDate("user_startday");

        Date stopday = cal.getDate("user_stopday");


        //2 把得到数据封装到数据里面去
        Calender calender =new Calender();
        calender.setWeek(week);
        calender.setTerm(term);
        calender.setStartday(startday);
        calender.setStopday(stopday);
        return calender;
    }
}

